/**
 * @program: LeetCode
 * @description: LeetCode : 二进制相加
 * @author: WXY
 * @create: 2022-12-11 16:49
 * @Version 1.0
 **/


public class Num_offer2_002_addBinary {
    public static String addBinary(String a, String b) {
        if (a == null || a.length() == 0) return b;
        if (b == null || b.length() == 0) return a;
        int i = a.length() - 1;
        int j = b.length() - 1;
        int c = 0;//进位
        StringBuilder sb = new StringBuilder();
        while (i >= 0 || j >= 0) {
            if (i >= 0) {
                c += a.charAt(i--) - '0';
            }
            if (j >= 0) {
                c += b.charAt(j--) - '0';
            }
            sb.append(c % 2);
            c >>= 1;
        }
        String s = sb.reverse().toString();
        return c > 0 ? '1' + s : s;
    }


    public static String addBinary1(String a, String b) {
        if (a == null || a.length() == 0) return b;
        if (b == null || b.length() == 0) return a;
        int i = a.length() - 1;
        int j = b.length() - 1;
        int c = 0;//进位
        StringBuilder stringBuilder = new StringBuilder();
        String str = "";
        while (i >= 0 || j >= 0) {
            int A = i >= 0 ? a.charAt(i--) - '0' : 0;
            int B = j >= 0 ? b.charAt(j--) - '0' : 0;
            int cur = (A + B + c) % 2;
            c = (A + B + c) / 2;
            stringBuilder.append(cur);
        }
        if (c == 1) stringBuilder.append(1);
        return stringBuilder.reverse().toString();
    }

    public static void main(String[] args) {
        String s = addBinary("101", "110");
        System.out.println(s);
    }
}
